﻿//https://leetcode.cn/problems/zui-xiao-de-kge-shu-lcof/description/
//堆排
class Solution {
public:
    vector<int> inventoryManagement(vector<int>& stock, int cnt) {
        if (cnt <= 0)return {};
        priority_queue<int> total(stock.begin(), stock.begin() + cnt);
        for (int i = cnt; i < stock.size(); i++)
        {
            if (stock[i] < total.top())
            {
                // cout<<" t:"<<stock[i];
                total.pop();
                total.push(stock[i]);
            }
        }
        vector<int> ret;
        while (!total.empty())ret.push_back(total.top()), total.pop();
        return ret;
    }
};
//快排
public:
    vector<int> getLeastNumbers(vector<int>& nums, int k)
    {
        srand(time(NULL));
        qsort(nums, 0, nums.size() - 1, k);
        return { nums.begin(), nums.begin() + k };
    }
    void qsort(vector<int>& nums, int l, int r, int k)
    {
        if (l >= r) return;
        // 1. 随机选择⼀个基准元素 + 数组分三块
        int key = getRandom(nums, l, r);
        int left = l - 1, right = r + 1, i = l;
        while (i < right)
        {
            if (nums[i] < key) swap(nums[++left], nums[i++]);
            else if (nums[i] == key) i++;
            else swap(nums[--right], nums[i]);
        }
        // [l, left][left + 1, right - 1] [right, r]
        // 2. 分情况讨论
        int a = left - l + 1, b = right - left - 1;
        if (a > k) qsort(nums, l, left, k);
        else if (a + b >= k) return;
        else qsort(nums, right, r, k - a - b);
    }
    int getRandom(vector<int>& nums, int l, int r)
    {
        return nums[rand() % (r - l + 1) + l];
    }
};